import type { Task, TaskStatus } from '@/types/task'
import type { User, UserProfile, UserStats } from '@/types/user'

// API 基础配置
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000/api'

class ApiService {
  private baseURL: string
  private token: string | null = null

  constructor(baseURL: string = API_BASE_URL) {
    this.baseURL = baseURL
    this.loadToken()
  }

  private loadToken() {
    this.token = localStorage.getItem('auth_token')
  }

  private saveToken(token: string) {
    this.token = token
    localStorage.setItem('auth_token', token)
  }

  private removeToken() {
    this.token = null
    localStorage.removeItem('auth_token')
  }

  // 通用 HTTP 方法
  private async request<T>(
    endpoint: string,
    options: RequestInit = {}
  ): Promise<T> {
    const url = `${this.baseURL}${endpoint}`
    const config: RequestInit = {
      ...options,
      headers: {
        'Content-Type': 'application/json',
        ...options.headers,
        ...(this.token && { Authorization: `Bearer ${this.token}` })
      }
    }

    try {
      const response = await fetch(url, config)
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      return await response.json()
    } catch (error) {
      console.error('API request failed:', error)
      throw error
    }
  }

  // 通用 GET 方法
  async get<T>(endpoint: string): Promise<T> {
    return this.request<T>(endpoint, { method: 'GET' })
  }

  // 通用 POST 方法
  async post<T>(endpoint: string, data?: any): Promise<T> {
    return this.request<T>(endpoint, {
      method: 'POST',
      body: data ? JSON.stringify(data) : undefined
    })
  }

  // 通用 PUT 方法
  async put<T>(endpoint: string, data?: any): Promise<T> {
    return this.request<T>(endpoint, {
      method: 'PUT',
      body: data ? JSON.stringify(data) : undefined
    })
  }

  // 通用 DELETE 方法
  async delete<T>(endpoint: string): Promise<T> {
    return this.request<T>(endpoint, { method: 'DELETE' })
  }

  // 认证相关
  async login(email: string, password: string): Promise<{ user: User; token: string }> {
    const result = await this.request<{ user: User; token: string }>('/auth/login', {
      method: 'POST',
      body: JSON.stringify({ email, password })
    })
    
    this.saveToken(result.token)
    return result
  }

  async register(userData: {
    username: string
    email: string
    password: string
  }): Promise<{ user: User; token: string }> {
    const result = await this.request<{ user: User; token: string }>('/auth/register', {
      method: 'POST',
      body: JSON.stringify(userData)
    })
    
    this.saveToken(result.token)
    return result
  }

  async logout(): Promise<void> {
    try {
      await this.request('/auth/logout', { method: 'POST' })
    } finally {
      this.removeToken()
    }
  }

  async getCurrentUser(): Promise<User> {
    return this.request<User>('/auth/me')
  }

  async refreshToken(): Promise<{ token: string }> {
    const result = await this.request<{ token: string }>('/auth/refresh', {
      method: 'POST'
    })
    
    this.saveToken(result.token)
    return result
  }

  // 用户相关
  async getUserProfile(): Promise<UserProfile> {
    return this.request<UserProfile>('/user/profile')
  }

  async updateUserProfile(profile: Partial<UserProfile>): Promise<UserProfile> {
    return this.request<UserProfile>('/user/profile', {
      method: 'PUT',
      body: JSON.stringify(profile)
    })
  }

  async changePassword(oldPassword: string, newPassword: string): Promise<void> {
    return this.request('/user/password', {
      method: 'PUT',
      body: JSON.stringify({ oldPassword, newPassword })
    })
  }

  async getUserStats(): Promise<UserStats> {
    return this.request<UserStats>('/user/stats')
  }

  // 任务相关
  async getTasks(params?: {
    status?: TaskStatus
    page?: number
    limit?: number
    search?: string
  }): Promise<{ tasks: Task[]; total: number; page: number; limit: number }> {
    const searchParams = new URLSearchParams()
    
    if (params?.status) searchParams.append('status', params.status)
    if (params?.page) searchParams.append('page', params.page.toString())
    if (params?.limit) searchParams.append('limit', params.limit.toString())
    if (params?.search) searchParams.append('search', params.search)

    const query = searchParams.toString()
    const endpoint = query ? `/tasks?${query}` : '/tasks'
    
    return this.request<{ tasks: Task[]; total: number; page: number; limit: number }>(endpoint)
  }

  async getTask(taskId: string): Promise<Task> {
    return this.request<Task>(`/tasks/${taskId}`)
  }

  async createTask(file: File, options: {
    outputFormat: string
    quality?: string
    customOptions?: Record<string, any>
  }): Promise<Task> {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('outputFormat', options.outputFormat)
    
    if (options.quality) {
      formData.append('quality', options.quality)
    }
    
    if (options.customOptions) {
      formData.append('customOptions', JSON.stringify(options.customOptions))
    }

    const headers: HeadersInit = {}
    if (this.token) {
      headers.Authorization = `Bearer ${this.token}`
    }

    const response = await fetch(`${this.baseURL}/tasks`, {
      method: 'POST',
      headers,
      body: formData
    })

    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}))
      throw new Error(errorData.message || '创建任务失败')
    }

    return response.json()
  }

  async cancelTask(taskId: string): Promise<void> {
    return this.request(`/tasks/${taskId}/cancel`, { method: 'POST' })
  }

  async retryTask(taskId: string): Promise<Task> {
    return this.request<Task>(`/tasks/${taskId}/retry`, { method: 'POST' })
  }

  async deleteTask(taskId: string): Promise<void> {
    return this.request(`/tasks/${taskId}`, { method: 'DELETE' })
  }

  async downloadTask(taskId: string): Promise<Blob> {
    const response = await fetch(`${this.baseURL}/tasks/${taskId}/download`, {
      headers: this.token ? { Authorization: `Bearer ${this.token}` } : {}
    })

    if (!response.ok) {
      throw new Error('下载失败')
    }

    return response.blob()
  }

  // 批量操作
  async batchCancelTasks(taskIds: string[]): Promise<void> {
    return this.request('/tasks/batch/cancel', {
      method: 'POST',
      body: JSON.stringify({ taskIds })
    })
  }

  async batchDeleteTasks(taskIds: string[]): Promise<void> {
    return this.request('/tasks/batch/delete', {
      method: 'POST',
      body: JSON.stringify({ taskIds })
    })
  }

  // 系统相关
  async getSystemStatus(): Promise<{
    status: 'healthy' | 'degraded' | 'down'
    version: string
    uptime: number
    activeUsers: number
    activeTasks: number
  }> {
    return this.request('/system/status')
  }

  async getSystemStats(): Promise<{
    totalTasks: number
    todayTasks: number
    totalUsers: number
    storageUsed: number
    storageTotal: number
  }> {
    return this.request('/system/stats')
  }

  // WebSocket 连接
  createWebSocket(path: string): WebSocket {
    const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
    const wsHost = this.baseURL.replace(/^https?:\/\//, '').replace(/\/api$/, '')
    const wsUrl = `${wsProtocol}//${wsHost}/ws${path}`
    
    const ws = new WebSocket(wsUrl)
    
    // 添加认证
    ws.addEventListener('open', () => {
      if (this.token) {
        ws.send(JSON.stringify({
          type: 'auth',
          token: this.token
        }))
      }
    })
    
    return ws
  }
}

// 创建单例实例
export const apiService = new ApiService()
export default apiService